package thread;

/**
 * NEW->RUNNABLE->TIMED_WAITING->RUNNABLE->TERMINATED
 */
public class ThreadStateNRTWRT {
    //锁
    private static final Object lock = new Object();

    public static void main(String[] args) {
        //展示线程
        Thread showThread = new Thread(new WaitTask());
        ThreadUtils.print(showThread.getName(), showThread.getState());
        showThread.start();
        ThreadUtils.print(showThread.getName(), showThread.getState());
        //循环读取展示线程状态，直到读到展示线程状态为TIMED_WAITING。
        while (true) {
            if (showThread.getState() == Thread.State.TIMED_WAITING) {
                ThreadUtils.print(showThread.getName(), Thread.State.TIMED_WAITING);
                break;
            }
        }

        try {
            showThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //线程执行完毕打印状态。
        ThreadUtils.print(showThread.getName(), showThread.getState());
    }


    private static class WaitTask implements Runnable {
        @Override
        public void run() {
            //等待
            synchronized (lock) {
                try {
                    lock.wait(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            ThreadUtils.print(Thread.currentThread().getName(), Thread.currentThread().getState());
        }
    }

}
